package com.tcj.blog.controller;

import com.tcj.blog.dto.JsonResult;
import com.tcj.blog.dto.ResponseCode;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 2 * @Author: Tcj
 * 3 * @Date: 2020/11/17 16:57
 * 4
 */
public class ControllerUtil {
    public static JsonResult getResult(DoThing doThing){
        JsonResult jsonResult = new JsonResult();
        try {
            doThing.doThing(jsonResult);
        } catch (Exception e) {
            jsonResult.setStatus(ResponseCode.ERROR);
            jsonResult.setMessage("未知错误，请联系管理员");
            jsonResult.setError(e);
            e.printStackTrace();
        }
        return jsonResult;
    }

    /**
     * 复制对象数据 将源对象的数据放到目标对象里。
     * @param src 源对象
     * @param dist 目标对象
     * @return
     */
    public static Object copyData(Object src,Object dist){
        Class<?> srcClass = src.getClass();
        Method[] methods = srcClass.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if ("set".equals(methodName.substring(0,3))){
               String getterName = methodName.replace("set","get");
                try {
                    Object data = srcClass.getMethod(getterName).invoke(src);
                    method.invoke(dist,data);
                } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException ignored) {
                }
            }
        }
        return  dist;
    }
}
